package com.spring.springboot.redis;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 15625
 * @date 2020-11-23 14:23
 * @description: redis测试
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@Slf4j
public class RedisDemo {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void redisAddDemo() {
        // 1、通过redisTemplate设置值
        redisTemplate.boundValueOps("name").set("宋义州", 60, TimeUnit.SECONDS);

        // 2、通过BoundValueOperations设置值
        BoundValueOperations<String, String> sex = redisTemplate.boundValueOps("sex");
        sex.set("男", 60, TimeUnit.SECONDS);

        // 3、通过ValueOperations设置值
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("idCart", "412724199612246414", 60, TimeUnit.SECONDS);
    }

    @Test
    public void redisGetDemo() {
        // 1、通过redisTemplate获取值
        String name = redisTemplate.boundValueOps("name").get();
        if (Strings.isNullOrEmpty(name)) {
            log.info("名字:{}", "数据已失效");
        } else {
            log.info("名字:{}", name);
        }

        // 2、通过BoundValueOperations获取值
        BoundValueOperations<String, String> sexKey = redisTemplate.boundValueOps("sex");
        String sexValue = sexKey.get();
        if (Strings.isNullOrEmpty(sexValue)) {
            log.info("性别:{}", "数据已失效");
        } else {
            log.info("性别:{}", sexValue);
        }

        // 3、通过ValueOperations获取值
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String idCart = opsForValue.get("idCart");
        if (Strings.isNullOrEmpty(idCart)) {
            log.info("身份证号码:{}", "数据已失效");
        } else {
            log.info("身份证号码:{}", idCart);
        }
    }

    @Test
    public void getList() {
        List<String> sysConfigCache = redisTemplate.opsForList().range("sysConfigCache", 0, -1);
        log.info("------获取缓存数据------>{}", sysConfigCache);
    }

}
